<template>
  <div class="app-container">
    <box-card class="box-card-query">
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="注册证书类型" prop="certificateType">
          <el-cascader v-model="queryParams.certificateType" placeholder="注册证书类型" :options="optionsCertificateTypes"
            :props="cascaderCertificateTypesProps" clearable style="min-width: 320px;" />
        </el-form-item>
        <el-form-item label="注册专业" prop="registerMajor">
          <el-input v-model="queryParams.registerMajor" placeholder="注册专业" clearable
            style="min-width: 320px; max-width: 320px;" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="归属地区" prop="registeredAreaId">
          <el-cascader v-model="queryParams.registeredAreaId" placeholder="归属地区" :options="optionsArea"
            :props="cascaderProps" clearable style="min-width: 320px;" />
        </el-form-item>
        <el-form-item label="证书编号" prop="certificateCode">
          <el-input v-model="queryParams.certificateCode" placeholder="证书编号" clearable
            style="min-width: 320px; max-width: 320px;" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="注册编号" prop="registerCode">
          <el-input v-model="queryParams.registerCode" placeholder="注册编号" clearable
            style="min-width: 320px; max-width: 320px;" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="注册单位" prop="registerCompany">
          <el-input v-model="queryParams.registerCompany" placeholder="注册单位" clearable
            style="min-width: 320px; max-width: 320px;" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="注册主体人" prop="registerPerson">
          <el-input v-model="queryParams.registerPerson" placeholder="注册主体人" clearable
            style="min-width: 320px; max-width: 320px;" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </box-card>

    <box-card class="mt24">
      <el-table v-loading="loading" :data="dataList" stripe>
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column label="证书编号" prop="certificateCode" width="120" />
        <el-table-column label="注册编号" prop="registerCode" width="120" />
        <el-table-column label="注册证书类型" prop="certificateTypeName" minWidth="200" />
        <el-table-column label="注册专业" prop="registerMajor" width="120" />
        <el-table-column label="注册单位" prop="registerCompany" minWidth="200" />
        <el-table-column label="注册主体人" prop="registerPerson" width="100" />
        <el-table-column label="归属单位" prop="registeredCompany" minWidth="200" />
        <el-table-column label="归属人" prop="registerPerson" width="100" />
        <el-table-column label="联系人" prop="contact" width="100" />
        <el-table-column label="联系电话" prop="contactMobile" minWidth="140" />
        <el-table-column label="来源" prop="sourceCompanyName" minWidth="200">
          <template #default="scope">
            <div>{{ scope.row.sourceCompanyName }} - {{ scope.row.sourceUserName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="线索状态" prop="status" width="100">
          <template #default="scope">
            <tag-view :options="cueStateList" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="160" />
        <el-table-column label="沟通记录" prop="communicateQty" width="100">
          <template #default="scope">
            <div>{{ scope.row.communicateQty && scope.row.communicateQty > 0 ? '有沟通记录' : '无沟通记录' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="140" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" v-if="scope.row.status === 1"
              @click="handleDistribution(scope.row)">分配</el-button>
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" v-if="scope.row.status === 1" @click="handleBack(scope.row)">释放</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </box-card>

    <el-dialog title="资质详情" v-model="detailOpen" :align-center="true" width="800px" append-to-body>
      <el-form :model="detail" :rules="detailRules" ref="detailRef" :inline="true" class="detail-form" label-width="80"
        label-position="left">
        <el-row>
          <el-col :span="8" class="sub-title">
            <svg-icon class-name="arrow-left" icon-class="arrow-left"></svg-icon>
            <span class="title">基本信息</span>
          </el-col>
          <el-col :span="16" class="flex justify-end">
            <el-button link type="primary" @click="kfOpen = true">资料错误，联系客服？</el-button>
          </el-col>
        </el-row>
        <el-row class="mt10">
          <el-col :span="12">
            <el-form-item label="资质编号" class="info-item">
              {{ detail.qualificationCode || '-' }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" class="info-item">
              {{ detail.status === 1 ? '已领用' : '已退回' }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资质类型" class="info-item">
              {{ detail.qualificationTypeName || '-' }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资质等级" class="info-item">
              {{ detail.qualificationLevel || '-' }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属公司" class="info-item">
              {{ detail.registeredCompany || '-' }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属地" class="info-item">
              {{ detail.registeredAreaName || '-' }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" class="info-item">
              {{ detail.contact || '-' }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" class="info-item">
              {{ detail.contactMobile || '-' }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="来源" class="info-item">
              {{ (detail.sourceCompanyName || '') + ' - ' + (detail.sourceUserName || '') }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" class="info-item">
              {{ detail.createTime }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="mt20">
          <el-col :span="12" class="sub-title">
            <svg-icon class-name="arrow-left" icon-class="arrow-left"></svg-icon>
            <span class="title">线索标记</span>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row class="mt20">
          <el-col :span="12">
            <el-form-item label="跟进级别" class="info-item" prop="followLevel">
              <el-select :disabled="detail.status === 0" v-model="detail.followLevel" placeholder="请选择跟进级别" clearable
                style="min-width: 240px; max-width: 320px;">
                <el-option v-for="dict in nvg_follow_level" :key="dict.value" :label="dict.label"
                  :value="Number(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线索级别" class="info-item" prop="clewType">
              <el-select :disabled="detail.status === 0" v-model="detail.clewType" placeholder="请选择线索级别" clearable
                style="min-width: 240px; max-width: 320px;">
                <el-option v-for="dict in nvg_clew_type" :key="dict.value" :label="dict.label"
                  :value="Number(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="mt20">
          <el-col :span="12" class="sub-title">
            <svg-icon class-name="arrow-left" icon-class="arrow-left"></svg-icon>
            <span class="title">跟进记录</span>
          </el-col>
          <el-col :span="12" class="flex justify-end">
            <el-button type="primary" :disabled="detail.status === 0" @click="handleAdd">新增跟进</el-button>
          </el-col>
        </el-row>
        <el-table class="mt15" v-loading="loading" :data="followList" stripe style="height: 240px;">
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column label="跟进时间" prop="followTime" />
          <el-table-column label="沟通记录" prop="record" />
          <el-table-column label="沟通结果" prop="survey" />
          <el-table-column label="跟进人" prop="followName" />
          <el-table-column label="操作" fixed="right" width="100" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" :disabled="detail.status === 0"
                @click="handleFollowEdit(scope.row)">编辑</el-button>
              <el-button link type="primary" :disabled="detail.status === 0"
                @click="handleFollowDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="clewTotal > 0" :total="clewTotal" v-model:page="form.pageNum" v-model:limit="form.pageSize"
          @pagination="fetchClewFollowList" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="detail.status === 0" @click="backSeas">退回公海池</el-button>
          <el-button type="primary" :disabled="detail.status === 0" @click="submitDetail">确 定</el-button>
          <el-button @click="cancelDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="新增跟进" v-model="addFollowOpen" :align-center="true" width="500px" append-to-body>
      <el-form :model="addFollowForm" :rules="addFollowRules" ref="addFollowRef" label-width="80">
        <el-form-item label="跟进人" prop="followName">
          <el-input v-model="addFollowForm.followName" placeholder="请输入跟进人" />
        </el-form-item>
        <el-form-item label="沟通记录" prop="record">
          <el-input v-model="addFollowForm.record" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea"
            placeholder="请输入沟通记录" />
        </el-form-item>
        <el-form-item label="沟通反馈" prop="survey">
          <el-input v-model="addFollowForm.survey" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea"
            placeholder="请输入沟通反馈" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddFollow">确 定</el-button>
          <el-button @click="cancelAddFollow">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="分配线索" v-model="distributionOpen" :align-center="true" width="800px" append-to-body>
      <el-table v-loading="loading" :data="staffList" stripe>
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column label="部门" prop="dept" />
        <el-table-column label="姓名" prop="realname" />
        <!-- <el-table-column label="当前获取线索数量" prop="itemName" /> -->
        <el-table-column label="操作" fixed="right" width="100" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleReceive(scope.row)">立即分配</el-button>
            <!-- <el-button link type="primary" @click="handleReceive(scope.row)">撤回</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="staffListTotal > 0" :total="staffListTotal" v-model:page="staffListQuery.pageNum"
        v-model:limit="staffListQuery.pageSize" @pagination="fetchStaffList" />
    </el-dialog>

    <el-dialog title="退回公海池" v-model="backOpen" :align-center="true" width="400px" append-to-body>
      <el-form :model="backClewForm" :rules="backRules" ref="backClewRef">
        <el-form-item label="原因" prop="reason">
          <el-input v-model="backClewForm.reason" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea"
            placeholder="请输入退回公海池的原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBack">确 定</el-button>
          <el-button @click="cancelBack">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="联系客服" v-model="kfOpen" :align-center="true" width="400px" append-to-body>
      <div style="display: flex; align-items: center; justify-content: center;">
        <img style="width: 250px; height: 406px;" src="@/assets/images/qrcode.png" alt="" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessageBox } from "element-plus"
import {
  getClewCertificateList, clewCertificateInfo,
  clewFollowList, returnClew, editClew,
  addClewFollow, editClewFollow, removeClewFollow,
  allotClew
} from '@/api/opensea'
import { getStaffList } from '@/api/member'
import { getAreas, getRegisterCertificateTypes } from '@/api/common'

const { proxy } = getCurrentInstance()
const { nvg_clew_type, nvg_follow_level } = proxy.useDict('nvg_clew_type', 'nvg_follow_level')

// 线索状态
const cueStateList = ref([{
  label: '使用中',
  value: 1,
}, {
  label: '已释放',
  value: 0,
}])

const cascaderProps = {
  value: 'id',
  label: 'areaName',
  expandTrigger: 'hover',
  checkStrictly: true,
  // emitPath: false,
}

const cascaderCertificateTypesProps = {
  value: 'id',
  label: 'name',
  expandTrigger: 'hover',
  checkStrictly: true,
  // emitPath: false, // 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
}

const optionsArea = ref([])

const optionsCertificateTypes = ref([])

const loading = ref(false)
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  certificateType: undefined,
  registerMajor: undefined,
  registeredAreaId: undefined,
  certificateCode: undefined,
  registerCode: undefined,
  registerCompany: undefined,
  registerPerson: undefined,
})
// 线索列表
const dataList = ref([])
// 打开线索详情
const detailOpen = ref(false)
// 线索详情数据
const detail = ref({})
// 跟进记录列表
const followList = ref([])
// 跟进记录列表loading
const followLoading = ref(false)
// 跟进记录列表搜索
const form = ref({
  pageNum: 1,
  pageSize: 10,
  clewId: undefined,
})
// 员工列表分页查询
const staffListQuery = ref({
  pageNum: 1,
  pageSize: 10,
  clewId: undefined,
})
// 员工列表
const staffList = ref([])
const staffListTotal = ref(0)
const distributionOpen = ref(false)
const backOpen = ref(false)
const clewTotal = ref(0)
const backClewForm = ref({
  id: undefined,
  reason: undefined,
})
// 新增跟进弹窗
const addFollowOpen = ref(false)
// 新增跟进表单
const addFollowForm = ref({
  clewId: undefined,
  followName: undefined,
  id: undefined,
  record: undefined,
  survey: undefined,
})
const kfOpen = ref(false)

const detailRules = {
  followLevel: [{ required: true, trigger: "change", message: "请选择跟进级别" }],
  clewType: [{ required: true, trigger: "change", message: "请选择线索级别" }],
}

const backRules = {
  reason: [{ required: true, trigger: "blur", message: "请输入退回公海池的原因" }],
}

const addFollowRules = {
  followName: [{ required: true, trigger: "blur", message: "请输入跟进人" }],
  record: [{ required: true, trigger: "blur", message: "请输入沟通记录" }],
  survey: [{ required: true, trigger: "blur", message: "请输入沟通反馈" }],
}
// 查询列表
function getList() {
  loading.value = true
  getClewCertificateList(queryParams.value).then(res => {
    loading.value = false
    if (res.code === 200) {
      dataList.value = res.data.list
      total.value = res.data.total
    }
  })
}
// 查询跟进列表
function fetchClewFollowList() {
  followLoading.value = true
  clewFollowList(form.value).then(res => {
    followLoading.value = false
    if (res.code === 200) {
      followList.value = res.data.list
      clewTotal.value = res.data.total
    }
  })
}
// 查询地区
function fetchAreas(parentId) {
  getAreas({ parentId }).then(res => {
    if (res.code === 200) {
      optionsArea.value = res.data
    }
  })
}
// 查询证书类型
function fetchRegisterCertificateTypes(parentId) {
  getRegisterCertificateTypes({ parentId }).then(res => {
    if (res.code === 200) {
      optionsCertificateTypes.value = res.data
    }
  })
}
// 查询员工列表
async function fetchStaffList() {
  const res = await getStaffList({
    pageNum: staffListQuery.value.pageNum,
    pageSize: staffListQuery.value.pageSize,
  })
  staffList.value = res.data.list
  staffListTotal.value = res.data.total
  return res
}
// 重置列表筛选
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}
// 查询列表
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
// 显示线索详情
async function handleDetail(item) {
  proxy.resetForm("detailRef")
  addFollowReset()
  const res = await clewCertificateInfo(item.id)
  detail.value = res.data
  form.value.clewId = detail.value.id
  backClewForm.value.id = detail.value.id
  await fetchClewFollowList()
  detailOpen.value = true
}
// 显示分配弹窗
async function handleDistribution(item) {
  staffListQuery.value.pageNum = 1
  staffListQuery.value.clewId = item.id
  await fetchStaffList()
  distributionOpen.value = true
}
// 释放
function handleBack(item) {
  backClewReset()
  backClewForm.value.id = item.id
  backOpen.value = true
}
// 提交详情
function submitDetail() {
  proxy.$refs.detailRef.validate(valid => {
    if (valid) {
      editClew({
        id: detail.value.id,
        clewType: detail.value.clewType,
        followLevel: detail.value.followLevel,
      }).then(res => {
        proxy.$modal.msgSuccess(res.data)
        getList()
        detailOpen.value = false
      })
    }
  })
}
// 取消详情弹窗
function cancelDetail() {
  detailOpen.value = false
}
// 新增跟进
function handleAdd() {
  addFollowReset()
  addFollowOpen.value = true
}
// 取消新增跟进弹窗
function cancelAddFollow() {
  addFollowOpen.value = false
  addFollowReset()
}
// 重置新增跟进
function addFollowReset() {
  addFollowForm.value = {
    followName: undefined,
    id: undefined,
    record: undefined,
    survey: undefined,
  }
  proxy.resetForm("addFollowRef")
}
// 新增跟进提交
function submitAddFollow() {
  proxy.$refs.addFollowRef.validate(valid => {
    if (valid) {
      console.log('addFollowForm:', addFollowForm.value)
      if (addFollowForm.value.id) {
        editClewFollow({
          ...addFollowForm.value,
          clewId: detail.value.id,
        }).then(res => {
          proxy.$modal.msgSuccess(res.data)
          form.value.pageNum = 1
          addFollowOpen.value = false
          fetchClewFollowList()
          addFollowReset()
        })
      } else {
        addClewFollow({
          ...addFollowForm.value,
          clewId: detail.value.id,
        }).then(res => {
          proxy.$modal.msgSuccess(res.data)
          form.value.pageNum = 1
          addFollowOpen.value = false
          fetchClewFollowList()
          addFollowReset()
        })
      }
    }
  })
}
// 跟进列表编辑
function handleFollowEdit(item) {
  addFollowReset()
  addFollowForm.value = { ...item }
  addFollowOpen.value = true
}
// 删除跟进记录
function handleFollowDelete(item) {
  ElMessageBox.confirm('您是否确认删除这条跟进记录', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    removeClewFollow(item.id).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess(res.data)
        form.value.pageNum = 1
        fetchClewFollowList()
      }
    })
  }).catch(() => { })
}
// 退回公海按钮
function backSeas() {
  backClewReset()
  backOpen.value = true
}
// 重置退回信息
function backClewReset() {
  proxy.resetForm("backClewRef")
}
// 退回公海池
function submitBack() {
  proxy.$refs.backClewRef.validate(valid => {
    if (valid) {
      returnClew({
        id: backClewForm.value.id,
        reason: backClewForm.value.reason,
      }).then(res => {
        proxy.$modal.msgSuccess(res.data)
        getList()
        backOpen.value = false
        detailOpen.value = false
      })
    }
  })
}
// 取消退回公海池弹窗
function cancelBack() {
  backOpen.value = false
  backClewReset()
}
// 立即分配
function handleReceive(item) {
  ElMessageBox.confirm(`您是否确认将这条线索立即分配给员工：“${item.realname}”`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    allotClew({
      clewId: staffListQuery.value.clewId,
      staffId: item.id,
    }).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess(res.data)
        queryParams.value.pageNum = 1
        distributionOpen.value = false
        getList()
      }
    })
  }).catch(() => { })
}

getList()
fetchAreas(100000)
fetchRegisterCertificateTypes(0)
</script>

<style lang="scss" scoped>
.box-card-query {
  padding-bottom: 0;
}

.sub-title {
  display: flex;
  align-items: center;
  font-size: 14px;

  .title {
    color: #333333;
    margin-left: 7px;
    margin-right: 5px;
  }
}

.detail-form {
  .info-item {
    margin-bottom: 0;
  }
}
</style>